package com.bhp.vblog.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @ClassName SpringBeanUtil
 * @Description TODO
 * @Author 包海鹏
 * @Date 2020/4/2 17:13
 * @Version 1.0
 **/
@Component
public class SpringBeanUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringBeanUtil.applicationContext = applicationContext;
    }

    /**
     * 获取applicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 通过class获取Bean
     *
     * @param cls 目标类
     * @param <T> 泛型类
     * @return 目标Bean
     */
    public static <T> T getBean(Class<T> cls) {
        return getApplicationContext().getBean(cls);
    }


}
